import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_changdian_football/api/api_response.dart';
import 'package:flutter_changdian_football/api/req/other/req_other.dart';
import 'package:flutter_changdian_football/api/req/user/req_user.dart';
import 'package:flutter_changdian_football/model/user/self_detail_model.dart';
import 'package:flutter_changdian_football/pages/mine/user_store.dart';
import 'package:flutter_changdian_football/utils/custom_logger.dart';
import 'package:flutter_changdian_football/utils/image_compress_util.dart';
import 'package:flutter_changdian_football/widget/dialog/operational_results_dialog.dart';
import 'package:flutter_changdian_football/widget/toast/custom_toast.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:image_picker/image_picker.dart';
import 'package:dio/dio.dart' as dio;

class PersonalInfoController extends GetxController {

  @override
  void onInit() {
    super.onInit();
    getUserInfo();
  }

  SelfDetailModel? selfDetailModel;
  // 擅长位置
  List goodPositionCode = [];

  TextEditingController nickNameController = TextEditingController();

  /// 获取用户信息
  getUserInfo() async {
    try {
      EasyLoading.show();
      var resp = await ReqUser.selfDetail();
      if (resp.status == Status.completed) {
        if (resp.data['code'] == '200') {
          selfDetailModel = SelfDetailModel.fromJson(resp.data['data']);
          goodPositionCode = selfDetailModel?.goodPosition?.map((item) => item.subdivisionPosition ?? '').toList() ?? [];
        }
      }
    } catch (e) {
      logger.d('获取用户自己的个人信息失败');
    } finally {
      EasyLoading.dismiss();
      update();
    }
  }

  /// 修改性别
  changeSex(p) {
    selfDetailModel?.sex = p == 0 ? '男' : '女';
    update();
  }

  changeHeight(k, v) {
    selfDetailModel?.height = '${v}cm';
    update();
  }

  changeWdight(k, v) {
    selfDetailModel?.weight = '${v}kg';
    update();
  }

  changeBirthday(p) {
    selfDetailModel?.birthday = p.toString().split(' ')[0];
    update();
  }

  changeNickName() {
    if (nickNameController.text.trim() == '') {
      CustomToast.showTextToast('请输入您的昵称');
      return ;
    }
    selfDetailModel?.nickname = nickNameController.text;
    update();
    Get.back();
  } 

  photoSelectImage() async {
    Get.back();
    final PickedFile? image = await ImagePicker().getImage(source: ImageSource.gallery);

    if (image != null) {
      addImage(image.path);
    }
  }

  shootSelectImage() async {
    Get.back();
    final PickedFile? photo = await ImagePicker().getImage(source: ImageSource.camera);
    if (photo != null) {
      addImage(photo.path);
    }
  }

  addImage(path) async {
    try {
      EasyLoading.show();
      File imageCompressedImage = await ImageCompressUtil().imageCompressAndGetFile(File(path));

      dio.FormData formData = dio.FormData.fromMap(
        {
          'file': await dio.MultipartFile.fromFile(imageCompressedImage.path),
          'businessType': 'USER_AVATAR'
        }
      );
      var resp = await ReqOther.fileUpload(formData);
      if (resp.status == Status.completed) {
        if (resp.data['code'] == '200') {
          selfDetailModel?.imageUrl = resp.data["data"];
          update();
        } else {
          CustomToast.showTextToast(resp.data['msg']);
        }
      } else {
        CustomToast.showTextToast('系统繁忙，请稍后再试！');
      }
    } catch (e) {
      CustomToast.showTextToast('系统繁忙，请稍后再试！');
    } finally {
      EasyLoading.dismiss();
    }
  }

  /// 确认修改
  comfirmUpdate() async {
    if (selfDetailModel?.nickname == null) {
      CustomToast.showTextToast('请输入昵称');
      return ;
    }
    if (selfDetailModel?.cityCode == null || selfDetailModel?.provinceCode == null) {
      CustomToast.showTextToast('请选择地区');
      return ;
    }
    if (selfDetailModel?.sex == null) {
      CustomToast.showTextToast('请选择性别');
      return ;
    }

    String subdivisionPositionCode = selfDetailModel?.goodPosition?.map((item) => item.subdivisionPositionCode ?? '').toList().join(',') ?? '';
    // 地区
    try {
      EasyLoading.show();

      var resp = await ReqUser.playerInfo(
        birthday: selfDetailModel?.birthday == null ? null : selfDetailModel?.birthday.toString().split(' ')[0],
        cityCode: selfDetailModel?.cityCode,
        cityName: selfDetailModel?.cityName,
        goodPositionCode: subdivisionPositionCode,
        height: int.tryParse('${selfDetailModel?.height?.replaceAll('cm', '')}') ?? 0,
        imageUrl: selfDetailModel?.imageUrl,
        name: selfDetailModel?.nickname,
        provinceCode: selfDetailModel?.provinceCode,
        provinceName: selfDetailModel?.provinceName,
        sex: selfDetailModel?.sex == '男' ? 0 : 1,
        weight: int.tryParse('${selfDetailModel?.weight?.replaceAll('kg', '')}') ?? 0,
      );
      if (resp.status == Status.completed) {
        if (resp.data['code'] == '200') {
          OperationalResultsDialog.show(
            Get.context!,
            text: '个人信息修改成功',
            icon: 'assets/images/img_tc_cg.png',
            confirmTap: () {
              Get.back();
              Get.back();
              UserStore.to.getUserInfo();
            }
          );
        } else {
          OperationalResultsDialog.show(
            Get.context!,
            text: resp.data['msg'],
            icon: 'assets/images/img_tc_sb.png',
            confirmTap: () {
              Get.back();
            }
          );
        }
      } else {
        OperationalResultsDialog.show(
          Get.context!,
          text: '个人信息修改失败',
          icon: 'assets/images/img_tc_sb.png',
          confirmTap: () {
            Get.back();
          }
        );
      }
    } catch (e) {
      OperationalResultsDialog.show(
        Get.context!,
        text: '个人信息修改失败',
        icon: 'assets/images/img_tc_sb.png',
        confirmTap: () {
          Get.back();
        }
      );
    } finally {
      EasyLoading.dismiss();
    }
  }

}